package com.eco.fanliapp.job.redmoneyjob;

import com.eco.fanliapp.dao.AppUserRedRewardMapper;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.vo.RedRewardInvitationListVo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @date 2020-01-10
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class InviteFansListTask implements Job, Serializable {
    @Autowired
    private AppUserRedRewardMapper appUserRedRewardMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;

    public InviteFansListTask(){}
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行邀请人数榜单任务-InviteFansListTask：executeCount="+executeCount+"--startTime="+startTime);
        java.util.Calendar cale = null;
        cale = java.util.Calendar.getInstance();
        int month = cale.get(Calendar.MONTH) + 1;
        int day = cale.get(Calendar.DATE);
        String key = "app_user_invite_fansNum_list_"+day;
        List<RedRewardInvitationListVo> listVo =  appUserRedRewardMapper.invitationfansNumber(month,0);
        if(listVo != null){
            for (RedRewardInvitationListVo vo:listVo
                 ) {
                //1随机数1-30 增加邀请人数，30%的增加概率
                Random random = new Random();
                int i = random.nextInt(100);
                if(i<30){
                    //随机增加邀请人数
                    int num = random.nextInt(5)+1;
                    log.info("随机增加人数"+num);
                    vo.setTotalAmount(vo.getTotalAmount()+num);
                    appUserRedRewardMapper.updateFansVoList(vo);
                }
            }
            redisTemplateService.del(key);
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行邀请人数榜单任务-InviteFansListTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }
}
